class PostsController < ApplicationController 
 
  include Skinning
 
  before_filter :login_required, :except => [:index, :show]
  before_filter :blog_required
  
  # GET /posts
  # GET /posts.xml
  def index
    @posts = Post.find(:all, :conditions => ["blog_id = ?", current_blog.id])
    
    respond_to do |format|
      format.html # index.rhtml
      format.xml  { render :xml => @posts.to_xml }
    end
  end
  
  # GET /posts/1
  # GET /posts/1.xml
  def show
    @post = Post.find(params[:id])
    
    respond_to do |format|
      format.html # show.rhtml
      format.xml  { render :xml => @post.to_xml }
    end
  end
  
  # GET /posts/new
  def new
    @post = Post.new
    @post.user = current_user
  end
  
  # GET /posts/1;edit
  def edit
    @post = Post.find(params[:id])
  end
  
  # POST /posts
  # POST /posts.xml
  def create
    @post = Post.new(params[:post])
    
    @post.blog = current_blog
    @post.user = current_user

    respond_to do |format|
      if @post.save
        flash[:notice] = 'Post was successfully created.'
        
        format.html { redirect_to posts_url }
        format.xml do
          headers["Location"] = post_url(@post)
          render :nothing => true, :status => "201 Created"
        end
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @post.errors.to_xml }
      end
    end
  end
  
  # PUT /posts/1
  # PUT /posts/1.xml
  def update
    @post = Post.find(params[:id])
    
    respond_to do |format|
      if @post.update_attributes(params[:post])
        format.html { redirect_to posts_url }
        format.xml  { render :nothing => true }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @post.errors.to_xml }
      end
    end
  end
  
  # DELETE /posts/1
  # DELETE /posts/1.xml
  def destroy
    @post = Post.find(params[:id])
    @post.destroy
    
    respond_to do |format|
      format.html { redirect_to posts_url   }
      format.xml  { render :nothing => true }
    end
  end
  
  private
    def blog_required
      if current_blog
        return true
      else
        render(:text => %{There is no blog named "#{params[:blog]}."},
          :status => 404, :layout => false) and return false
      end
    end
end